<template>
  <view class="address-list">
    <!-- 地址列表 -->
    <view class="address-container" v-if="addressList.length > 0">
      <view 
        class="address-item" 
        v-for="(item, index) in addressList" 
        :key="index"
      >
        <view class="address-info" @tap="selectAddress(item)">
          <view class="user-info">
            <text class="name">{{item.name}}</text>
            <text class="phone">{{item.phone}}</text>
            <text class="tag" v-if="item.isDefault === true">默认</text>
          </view>
          <view class="address-detail">
            {{item.provinceName}}{{item.cityName}}{{item.districtName}}{{item.detail}}
          </view>
        </view>
        <view class="address-actions">
          <view class="action-item" @tap="editAddress(item)">
            <text class="iconfont icon-edit">✏️</text>
            <text>编辑</text>
          </view>
          <view class="action-item" @tap="deleteAddress(item)">
            <text class="iconfont icon-delete">🗑️</text>
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text class="iconfont icon-address-empty">📭</text>
      <text class="empty-text">暂无收货地址</text>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button">
      <button class="add-address" @tap="goToAddAddress">
        <text class="iconfont icon-add">➕</text>
        <text>新增收货地址</text>
      </button>
    </view>
  </view>
</template>

<script>
import { addressApi } from '@/api/address'

export default {
  data() {
    return {
      addressList: [],
      isSelect: false, // 是否是选择地址模式
      userId: null
    }
  },

  onLoad(options) {
    // 判断是否是选择地址模式
    if (options.select) {
      this.isSelect = true
    }
    
    // 获取用户信息
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.id) {
      this.userId = userInfo.id
    }
  },

  onShow() {
    this.getAddressList()
  },

  methods: {
    async getAddressList() {
      try {
        // 检查登录状态
        const token = uni.getStorageSync('token')
        const userInfo = uni.getStorageSync('userInfo')
        
        console.log('当前用户信息:', userInfo)
        
        if (!token || !userInfo || !userInfo.id) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          
          // 延迟跳转到登录页
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            })
          }, 1500)
          return
        }

        console.log('开始获取地址列表, userId:', userInfo.id)
        const res = await addressApi.getAddressList(userInfo.id)
        console.log('获取地址列表响应:', res)
        
        if (res.code === 200) {
          // 直接使用后端返回的数据
          this.addressList = res.data || []
          console.log('更新后的地址列表:', this.addressList)
        } else {
          throw new Error(res.msg || res.errorMessage || '获取地址列表失败')
        }
      } catch (error) {
        console.error('获取地址列表失败:', error)
        uni.showToast({
          title: error.message || '获取地址列表失败',
          icon: 'none'
        })
      }
    },

    selectAddress(address) {
      if (!this.isSelect) return
      
      // 选择地址后返回上一页
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      
      if (prevPage) {
        // 设置上一页的地址信息
        prevPage.$vm.setAddress(address)
      }
      
      uni.navigateBack()
    },

    goToAddAddress() {
      if (!this.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: '/pages/address/address-add'
      })
    },

    editAddress(address) {
      // 使用后端返回的addressId字段
      const addressId = address.addressId;
      
      if (!addressId) {
        console.error('无法找到地址ID:', address);
        uni.showToast({
          title: '编辑失败，无法获取地址ID',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
        url: `/pages/address/address-add?id=${addressId}`
      });
    },

    async deleteAddress(address) {
      if (!this.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      // 使用后端返回的addressId字段
      const addressId = address.addressId;
      
      if (!addressId) {
        console.error('无法找到地址ID:', address);
        uni.showToast({
          title: '删除失败，无法获取地址ID',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await addressApi.deleteAddress(addressId, this.userId)
              if (result.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.getAddressList()
              } else {
                throw new Error(result.msg || result.errorMessage || '删除地址失败')
              }
            } catch (error) {
              console.error('删除地址失败:', error)
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.address-list {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;

  .address-container {
    padding: 20rpx;

    .address-item {
      background: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

      .address-info {
        border-bottom: 2rpx solid #f5f5f5;
        padding-bottom: 20rpx;
        margin-bottom: 20rpx;

        .user-info {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;

          .name {
            font-size: 32rpx;
            font-weight: 500;
            color: #333;
            margin-right: 20rpx;
          }

          .phone {
            font-size: 28rpx;
            color: #666;
          }

          .tag {
            margin-left: 20rpx;
            font-size: 20rpx;
            color: #ff6b00;
            border: 2rpx solid #ff6b00;
            padding: 2rpx 12rpx;
            border-radius: 20rpx;
          }
        }

        .address-detail {
          font-size: 28rpx;
          color: #333;
          line-height: 1.5;
        }
      }

      .address-actions {
        display: flex;
        justify-content: flex-end;
        gap: 30rpx;

        .action-item {
          display: flex;
          align-items: center;
          gap: 8rpx;

          .iconfont {
            font-size: 32rpx;
            color: #666;
          }

          text {
            font-size: 26rpx;
            color: #666;
          }
        }
      }
    }
  }

  .empty-state {
    padding: 120rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .iconfont {
      font-size: 96rpx;
      color: #999;
      margin-bottom: 20rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .bottom-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx;
    background: #fff;
    box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);

    .add-address {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      height: 88rpx;
      background: #ff6b00;
      color: #fff;
      font-size: 32rpx;
      border-radius: 44rpx;
      border: none;

      .iconfont {
        font-size: 36rpx;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style> 